from fastapi import APIRouter
from fastapi.responses import JSONResponse
from fastapi import Form
from starlette.responses import FileResponse
from starlette.responses import RedirectResponse
from database import get_user, get_logging, create_table_login_data, insert_login_data, get_login_data1, get_information
from utils import name_mapping

router = APIRouter()  # 创建一个路由器实例


@router.get("/login")
async def login():
    return FileResponse('static/login.html')


@router.post("/login")
async def login_post(username: str = Form(...), password: str = Form(...)):
    create_table_login_data()
    insert_login_data(username)
    if not username or not password:
        return FileResponse('static/login.html')  # 确保HTML文件位于static文件夹中
    user = get_user(username)
    if not user or user['password'] != password:  # 注意：这里应该使用加密/哈希比较
        return JSONResponse(status_code=400, content={"detail": "Invalid username or password"})
    else:
        print('success')
        return RedirectResponse(url=f"/login/{username}")


@router.post("/login/{username}")
async def login_user(username: str):
    return FileResponse('static/menu.html')  # 确保HTML文件位于static文件夹中


@router.post("/data")
async def data():
    data = get_login_data1()
    name = data['username']
    username = name_mapping.get(name, None)
    if username is None:
        return {"error": "Invalid username"}
    info = get_information(username)
    return info


@router.post("/data1")
@router.get("/data1")
async def data1():
    info = get_logging()
    return info


@router.get("/")
async def index():
    return RedirectResponse("/login")

def get_routes():
    return router